// pages/search/search.js
const app = getApp()
const debounce = app.require("lib/debounce")
const db = wx.cloud.database()

// 引入mixins
const history = require("./mixins/history")
Page({
	mixins: [history],
	data: {
		focus: false,
		search: {
			content: "",
			flag: true,
			wordList: []
		}
	},
	onLoad(options) {
		this.initHistory()
		this.setData({ focus: true })
	},

	searchWord: debounce(async function () {
		// 查询联想词
		if (!this.data.search.content) return
		wx.showLoading({
			title: '搜索中',
		})
		const reg = new RegExp(`${this.data.search.content}`, "i")
		const getUser = db.collection("user").aggregate().project({
			nickName: true,
			_id: true
		})
			.match({
				"nickName": reg
			})
			.limit(10)
			.end()
		const getPost = db.collection("post").aggregate().project({
			title: true
		})
			.match({
				"title": reg
			})
			.limit(10)
			.end()
		const res = await Promise.all([getUser, getPost])
		wx.hideLoading()
		this.setData({ "search.wordList": { user: res[0].list, post: res[1].list } })
	}, 300),
	searchFocus() {
		// 输入框聚焦
		this.setData({ "search.flag": true })
	},
	changeContent(e) {
		// 输入框输入内容
		this.setData({ "search.content": e.detail })
		if (e.detail) {
			this.searchWord()
		}
		else {
			this.setData({ "search.wordList": {} })
		}
	},
	showPost(e) {
		// 跳转至文章详情
		const post = e.currentTarget.dataset.item
		this.addHistory(post.title)
		const { showPostDetail } = app.require("utils/router/post")
		showPostDetail(post._id)
	},
	showUser(e) {
		// 跳转至用户主页
		const user = e.currentTarget.dataset.item
		this.addHistory(user.nickName)
		const { showUserPage } = app.require("utils/router/user")
		showUserPage(user._id)
	},

})